//
//  YDInPositonViewController.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2018/1/16.
//  Copyright © 2018年 LK-IOS. All rights reserved.
//

#import "YDInPositonViewController.h"
#import "YDPositionInPositonCell.h"
#import "YDPositionModel.h"
#import "YDPointSaleConfirPopController.h"
#import "YDPointSaleConfirModelController.h"
#import "YDVerticalStockBuyController.h"



@interface YDInPositonViewController ()<UITableViewDelegate , UITableViewDataSource , SYPositionInPositonCellDelegate , UIViewControllerTransitioningDelegate , UIViewControllerAnimatedTransitioning , SYNoDataViewDelegate , SYPointSaleConfirModelControllerDelegate>

//顶部安全区域
@property (nonatomic , assign) CGFloat safeTopH;
//底部安全区域
@property (nonatomic , assign) CGFloat safeBottomH;
//当前页码
@property (nonatomic , assign) NSInteger currentPage;
//tableView
@property (nonatomic , weak) UITableView *tableView;

@property (nonatomic , strong) NSMutableArray *modelArray;

//记录弹出还是消失
@property (nonatomic , assign) BOOL onAnimate;

//无数据
@property (nonatomic , weak) SYNoDataView *dataView;
//网络占位图
@property (nonatomic, weak) SYNoNetView *noNetView;


//定时器
@property (nonatomic , strong) NSTimer *positionTimer;
//是不是正在刷新
@property (nonatomic , assign) BOOL positionTimerIsRunning;



@end

@implementation YDInPositonViewController

-(NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

-(void)viewDidLoad
{
    [super viewDidLoad];//mainGray
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    self.safeTopH = isPhoneX ? 84 : 64;
    self.safeBottomH = self.isHiddenTabbar ? 0 : (isPhoneX ? 83 : 49);
    [self tableView];
    [self setUpDataManger];
    
    [self addNotification];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self loadData];
    
    [self viewOpenTimer];
    
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [self viewStopTimer];
}

- (void)removeNoNetView
{
    if (_noNetView != nil) {
        [_noNetView removeFromSuperview];
        _noNetView = nil;
    }
}

- (void)removeNodataView
{
    if (_dataView != nil) {
        [_dataView removeFromSuperview];
        _dataView = nil;
    }
}
//******开始通知*******//
-(void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewOpenTimer) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewStopTimer) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewStopTimer) name:UIApplicationWillTerminateNotification object:nil];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)viewOpenTimer
{
    if (self.positionTimer)return;
    if (![NSDate stockTradingTimeJudgment])return;
    DDLog(@"开启定时器")
    
    self.positionTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timeLoadPositionStockData) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.positionTimer forMode:NSRunLoopCommonModes];
}
-(void)viewStopTimer
{
    if (!self.positionTimer)return;
    DDLog(@"关闭定时器")
    [self.positionTimer invalidate];
    self.positionTimer = nil;
}


/*******tableView********/
-(UITableView *)tableView
{
    if (_tableView == nil) {
        CGFloat tableH = LKScreenH - self.safeTopH - self.safeBottomH;
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, tableH) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.backgroundColor = [UIColor colorWithHexString:mainGray];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.scrollIndicatorInsets = tableView.contentInset;
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
    }
    return _tableView;
}

/**
 刷新控件
 */
-(void)setUpDataManger
{
    MJGIFHeader *header = [MJGIFHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    header.lastUpdatedTimeLabel.hidden = YES ;
    header.stateLabel.hidden = YES ;
    header.label.hidden = YES;
    self.tableView.mj_header = header;
    //    [self.tableView.mj_header beginRefreshing];
    
    
    MJGIFFooter *footer = [MJGIFFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.stateLabel.hidden = YES;
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}


/*******dataView********/
-(SYNoDataView *)dataView
{
    if (_dataView == nil) {
        CGFloat dataW = rate375(240);
        CGFloat dataX = (LKScreenW - dataW) * 0.5;
        CGFloat dataH = isPhoneX ? rateX812(276) : rate750(276);
        CGFloat dataY = isPhoneX ? rateX812(100) : rate750(100);
        CGRect frame = CGRectMake(dataX, dataY, dataW, dataH);
        //wuneirong   wuxinhao
        SYNoDataView *dataView = [SYNoDataView positionNoDataViewInitWithFrame:frame ImageString:@"wuneirong" buttonTitle:@"发布策略" IsCanSeeBuyButton:YES];
        dataView.delegate = self;
        dataView.isCanSeeBuyButton = YES;
        [self.tableView addSubview:dataView];
        _dataView = dataView;
    }
    return _dataView;
}
#pragma SYNoDataViewDelegate
-(void)noDataView:(SYNoDataView *)noDataView didClickSaleButton:(SYNoHeightedButton *)button
{
    YDVerticalStockBuyController *vc = [[YDVerticalStockBuyController alloc] init];
    vc.isNormal = YES;
    vc.isPopToRootC = NO;
    vc.isActivity = NO;
    vc.optionStyle = SYVerticalStockButtonOptionViewStyle0;
    vc.stockCode = @"000001";
    vc.stockName = @"平安银行";
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

-(SYNoNetView *)noNetView
{
    if (_noNetView == nil) {
        SYNoNetView *noNetView = [[SYNoNetView alloc] init];
        [self.tableView addSubview:noNetView];
        
        [noNetView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(isPhoneX ? @(rateX812(40)) : @(rate750(40)));
        }];
        LK(weself)
        [noNetView setClickBlock:^(BOOL isClick) {
            [weself.tableView.mj_header beginRefreshing];
            
        }];
        _noNetView = noNetView;
    }
    return _noNetView;
}

//////*******加载数据********//////
-(void)loadData
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(0) forKey:@"page"];
    [dict setObject:@(10) forKey:@"size"];
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:PositionInPositon WithSuccessBlock:^(NSDictionary *resultDict) {
        
        //        DDLog(@"resultDict = %@" , resultDict)
        
        [self.tableView.mj_header endRefreshing];
        
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [self.modelArray removeAllObjects];
            self.currentPage = [resultDict[@"result"][@"number"] integerValue] + 1;
            self.modelArray = [YDPositionModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"content"]];
            
            
            if (self.modelArray.count <10) {
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshing];
            }
            
            if (self.modelArray.count) {
                [self removeNoNetView];
                [self removeNodataView];
                
                
            }else{
                [self removeNoNetView];
                [self removeNodataView];
                [self dataView];
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
        }else{
            self.tableView.mj_footer.hidden = YES;
            
            if (self.modelArray.count) {
                [self.modelArray removeAllObjects];
                [self.tableView reloadData];
            }
            [self removeNoNetView];
            [self removeNodataView];
            [self noNetView];
            
        }
    } failBlock:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        self.tableView.mj_footer.hidden = YES;
        [self.tableView.mj_header endRefreshing];
        if (self.modelArray.count) {
            [self.modelArray removeAllObjects];
            [self.tableView reloadData];
        }
        
        [self removeNoNetView];
        [self removeNodataView];
        
        [self noNetView];
        
    }];
}

-(void)loadMoreData
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(self.currentPage) forKey:@"page"];
    [dict setObject:@(10) forKey:@"size"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:PositionInPositon WithSuccessBlock:^(NSDictionary *resultDict) {
        //        DDLog(@"resultDict%@",resultDict)
        if ([resultDict[@"code"] integerValue] == 200) {
            
            self.currentPage = [resultDict[@"result"][@"number"] integerValue] + 1;
            
            NSArray *array = [YDPositionModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"content"]];
            [self.modelArray addObjectsFromArray:array];
            
            [self.tableView reloadData];
            
            if (array.count <10) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
            
        }else{
            [[SYProgressHUD sharedInstance] showSVOnlytextWithText:@"加载出错"];
            [[SYProgressHUD sharedInstance] dismissSVWithTime:1];
            [self.tableView.mj_footer endRefreshing];
            
        }
    } failBlock:^(NSError *error) {
        //        DDLog(@"%@",error)
        [[SYProgressHUD sharedInstance] showSVOnlytextWithText:@"加载出错"];
        [[SYProgressHUD sharedInstance] dismissSVWithTime:1];
        [self.tableView.mj_footer endRefreshing];
    }];
}
#pragma UITableViewDelegate , UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return isPhoneX ? rateX812(180) : rate750(180);
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    YDPositionInPositonCell *cell = [YDPositionInPositonCell cellWithTableView:tableView];
    cell.delegate = self;
    
    YDPositionModel *model = self.modelArray[indexPath.row];
    
    cell.model= model;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.modelArray.count) {
        YDPositionModel *model = self.modelArray[indexPath.row];
        YDVerticalStockBuyController *vc = [[YDVerticalStockBuyController alloc] init];
        vc.isNormal = YES;
        vc.isActivity = NO;
        vc.optionStyle = SYVerticalStockButtonOptionViewStyle0;
        vc.stockCode = model.stockCode;
        vc.stockName = model.stockName;
        vc.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:vc animated:YES];
    }
}

/////**********************PZPositionInPositonCellDelegate**********************////////
-(void)inPositonCellSaleButonCLick:(YDPositionInPositonCell *)positionInPositonCell
{
    
    //非交易时间段弹窗
    if(![NSDate stockTradingTimeJudgment])
    {
        [self noTransactionTimeAlert];
        return;
    }
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:positionInPositonCell];
    YDPositionModel *model = self.modelArray[indexPath.row];
    YDPointSaleConfirModelController *vc = [[YDPointSaleConfirModelController alloc] init];
    vc.model = model;
    vc.delegate = self;
    vc.transitioningDelegate = self;
    vc.modalPresentationStyle = UIModalPresentationCustom;
    [self.navigationController presentViewController:vc animated:YES completion:nil];
}


- (void)noTransactionTimeAlert
{
    //非交易时间段弹窗
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"现在是非交易时间段，请在交易时间内点卖。\n交易时间段：（国家法定节假日除外）周一至周五\n09:30-11:30 13:00-14:50" ButtonTitle:@"我知道了" ButtonClickBlock:^{
        
        
        [self.pz_popupController dismiss];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}
/////**********************PZPointSaleConfirModelControllerDelegate**********************////////
-(void)saleConfirSuccess
{
    [self loadData];
}


#pragma mark  UIViewControllerTransitioningDelegate , UIViewControllerAnimatedTransitioning
//拿到负责自定义动画的控制器
-(UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source
{
    return [[YDPointSaleConfirPopController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
}
//谁负责弹出动画
-(id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    self.onAnimate = NO;
    return self;
}
//谁负责消失动画
-(id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    self.onAnimate = YES;
    return self;
}


#pragma mark UIViewControllerAnimatedTransitioning
//返回一个弹出和消失的时间
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext
{
    return 1.0;
}

//实现代理方法.做自定义转场动画
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
    if (self.onAnimate) {//弹出
        [self animateTransitionPresentedController:transitionContext];
    }else{//消失
        [self animateTransitionDismissedController:transitionContext];
    }
    
}

//弹出时调用
-(void)animateTransitionPresentedController:(id <UIViewControllerContextTransitioning>)transitionContext
{
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    [[transitionContext containerView] addSubview:toView];
    
    //    toView.transform = CGAffineTransformMakeScale(0.0, 0.0);
    toView.alpha = 0.0;
    [UIView animateWithDuration:duration animations:^{
        //        toView.transform = CGAffineTransformIdentity;
        toView.alpha = 1.0;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
}
//消失时调用
-(void)animateTransitionDismissedController:(id <UIViewControllerContextTransitioning>)transitionContext
{
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    [UIView animateWithDuration:duration animations:^{
        //        fromView.transform = CGAffineTransformMakeScale(0.00001, 0.00001);
        fromView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
}

-(void)timeLoadPositionStockData
{
    if (self.positionTimerIsRunning || !self.modelArray.count)return;
    self.positionTimerIsRunning = YES;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(0) forKey:@"page"];
    [dict setObject:@(30) forKey:@"size"];
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:PositionInPositon WithSuccessBlock:^(NSDictionary *resultDict) {
        self.positionTimerIsRunning = NO;
        
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [self.modelArray removeAllObjects];
            self.currentPage = [resultDict[@"result"][@"number"] integerValue] + 1;
            self.modelArray = [YDPositionModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"content"]];
            
            if (self.modelArray.count <10) {
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshing];
            }
            [self.tableView reloadData];
        }else{
        }
    } failBlock:^(NSError *error) {
        self.positionTimerIsRunning = NO;
    }];
}


@end
